<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-13
 * Time: 11:18:10
 * Info:
 */

namespace plugin\huiblog\app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

class Handler extends \support\exception\Handler
{

    public function render(Request $request, Throwable $exception): Response
    {
        $code = $exception->getCode();
        $debug = $this->_debug ?? $this->debug;
        if ($request->expectsJson()) {
            $json = [
                'code' => $code ?: 500,
                'msg'  => $debug ? $exception->getMessage() : 'Server internal error',
                'type' => 'failed'
            ];
            $debug && $json['traces'] = (string)$exception;

            return new Response(200, ['Content-Type' => 'application/json'],
                \json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }
        $error = $debug ? \nl2br((string)$exception) : 'Server internal error';

        return new Response(500, [], $error);
    }
}
